#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<linux/stat.h>
#include<signal.h>

#define PUBLIC_FIFO "PUBFIFO"
#define PRIVATE2_FIFO "PRIFIFO2"
#define PRIVATE2_HEADER "Client2's message:"

int main(int argc,char *argv[])
{
        int fd;
        int fd2;
        pid_t pid;
        char num[100]="";
        char buf[200]="";
        char str[100]=PRIVATE2_HEADER;

        if((fd2=open(PRIVATE2_FIFO,O_RDONLY)) == -1)
	{
		printf("Open fail.\n");
		exit(1);
	}
	if(read(fd2,buf,200)!=-1)
	{
		printf("%s\n",buf);
		close(fd2);
	}
	usleep(200000);

        pid=fork();
        if(pid<0)
        {
                printf("error");
        }
        else if(pid == 0){
                while(1)
                {
                        memset(buf, 0, 200);
                        if((fd2=open(PRIVATE2_FIFO,O_RDONLY))==-1)
                        {
                                printf("Open fail.\n");
                                exit(1);
                        }
                        if(read(fd2,buf,200)!=-1)
                        {
                                printf("%s\n",buf);
                                close(fd2);
                        }
                        usleep(200000);
                }
                
        }
        
        
        else
        {
                while(1)
                {
                        if((fd=open(PUBLIC_FIFO,O_WRONLY)) == -1)
                        {
                                printf("Open failed.\n");
                                exit(1);
                        }
                        memset(num,0,100);
                        fgets(num,100,stdin);
                        if(strncmp(num,"end",3) == 0)
                        {
                                kill(pid, SIGSTOP);     // 结束子进程
                                usleep(200000);
                                unlink(PRIVATE2_FIFO);  // 删除管道文件
                                printf("Bye!\n");
                                exit(0);
                        }
                        strcpy(str,PRIVATE2_HEADER);
                        strcat(str,num);
                        // printf("write str: %s\n", str);
                        if(write(fd,str,strlen(str))>0)
                        {
                                close(fd);
                        }
                        usleep(200000);
                }
                
        }
        
        return 0;

}

